package com.zhuoli.service.schedule.thread.pool.executor.task;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhuoli
 * @Date: 2018/9/5 21:26
 * @Description:
 */
//@Component
public class ScheduleWithFixedDelayTask {

    @PostConstruct
    public void starkTask(){
        TimerTask task1 = new TimerTask() {
            @Override
            public void run() {
                //获得该任务该次执行的期望开始时间
                System.out.println("expect start time: " + new Date(scheduledExecutionTime()));
                System.out.println("task1 start: " + new Date());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                }
                System.out.println("task1 end: " + new Date());
            }
        };

        System.out.println("now: " + new Date());
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(2);
        executor.scheduleWithFixedDelay(task1, 0, 1000, TimeUnit.MILLISECONDS);
    }
}
